using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Admin.NET.Application.DL645;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Enums;
using Admin.NET.Application.GuangHeMeter;
using Admin.NET.Application.GuangHeMeter.ServerSocket;
using Admin.NET.Application.Mqtt.mqttresponse;
using Admin.NET.Application.Service.Electricity;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Furion.FriendlyException;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Admin.NET.Application.Job;

[JobDetail("job_readjishemeter", Description = "集设电表读取", GroupName = "default", Concurrent = false)]
[PeriodMinutes(50L, TriggerId = "trigger_readjishemeter", Description = "集设电表读取", RunOnStart = false)]
public class ReadMeterByJS376 : IJob
{
	private readonly IServiceScopeFactory _scopeFactory;

	public ReadMeterByJS376(IServiceScopeFactory scopeFactory)
	{
		_scopeFactory = scopeFactory;
	}

	public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
	{
		using IServiceScope serviceScope = _scopeFactory.CreateScope();
		SqlSugarRepository<ElectricMeter> meterServer = serviceScope.ServiceProvider.GetService<SqlSugarRepository<ElectricMeter>>();
		List<ElectricMeter> listMeter = await (from u in meterServer.AsQueryable()
			where u.BrandId == 38066501696069L && u.SignalStatus == 1
			select u).ToListAsync();
		DL645Agreement dL645Agreement = new DL645Agreement();
		Thread.Sleep(10000);
		foreach (ElectricMeter item in listMeter)
		{
			try
			{
				LoggerExtension.Info("开始集中超标块表" + item.Sn + "----" + item.LowAddr);
				(IAggrementPlugin, BrandModel) plugin = AggrementPluginUtil.GetPlugin(item);
				var (pluginService, _) = plugin;
				_ = plugin.Item2;
				Dictionary<string, UploadMqttInfo> dic = new Dictionary<string, UploadMqttInfo>();
				UploadMqttInfo uploadMqttInfo = new UploadMqttInfo();
				EPowerService ePowerService = new EPowerService();
				LoggerExtension.Info("开始集中超标块表总电量" + item.Sn + "----" + item.LowAddr);
				string allRotal = pluginService.ReadCombinedTotalE(item.Sn, item.LowAddr, "jishe");
				uploadMqttInfo.Alltotal = allRotal;
				LoggerExtension.Info("开始集中超标块表总电量结束" + item.Sn + "----" + item.LowAddr);
				byte[] byteData = new byte[4] { 1, 1, 1, 3 };
				byte[] byteDataResult = BaseUtil.Get3761Data1(byteData, item.Sn);
				LoggerExtension.Info("开始电压电流功率" + item.Sn + "----" + item.LowAddr);
				string body = await pluginService.Transform(item.Sn, string.Join("", byteDataResult.Select((byte u) => u.ToString("x2")).ToArray()));
				LoggerExtension.Info("开始电压电流功率结束" + item.Sn + "----" + item.LowAddr);
				Console.WriteLine(body);
				string[] arr = ParseDLT645Result(body);
				if (arr.Length < 9)
				{
					break;
				}
				for (int i = 0; i < arr.Length; i++)
				{
					if (!double.TryParse(arr[i], out var _))
					{
						arr[i] = "0";
					}
				}
				uploadMqttInfo.ActivePowerAll = $"{arr[6]},{arr[7]},{arr[8]},{arr[9]}";
				uploadMqttInfo.CurrentAll = $"{arr[0]},{arr[1]},{arr[2]}";
				uploadMqttInfo.VoltageAll = $"{arr[3]},{arr[4]},{arr[5]}";
				byte[] bytedatatrain = new byte[4] { 2, 107, 100, 100 };
				string stateInfo = "68AAAAAAAAAAAA68110436383337B916";
				byte[] dlt645 = new byte[stateInfo.Length / 2];
				for (int i = 0; i < dlt645.Length; i++)
				{
					dlt645[i] = (byte)Convert.ToInt32(stateInfo.Substring(i * 2, 2), 16);
				}
				byte[] byteDataStateResult = BaseUtil.GetTransbyte(bytedatatrain, dlt645, item.Sn);
				LoggerExtension.Info("开始状态" + item.Sn + "----" + item.LowAddr);
				string[] result645 = ParseDLT645Result(await pluginService.Transform(item.Sn, string.Join("", byteDataStateResult.Select((byte u) => u.ToString("x2")).ToArray())));
				LoggerExtension.Info("开始状态结束" + item.Sn + "----" + item.LowAddr);
				string result = ParseDLT645(string.Join("", result645));
				uploadMqttInfo.State = result;
				Console.WriteLine("开始抄冻结数据");
				byte[] byteinfoyear = dL645Agreement.Send645Agreement(AgreementaType.Reading, "AAAAAAAAAAAA", "34333438").ToArray().Skip(4)
					.ToArray();
				byte[] byteinfo = dL645Agreement.Send645Agreement(AgreementaType.Reading, "AAAAAAAAAAAA", "34343438").ToArray().Skip(4)
					.ToArray();
				BaseUtil.GetTransbyte(bytedatatrain, byteinfoyear, item.Sn);
				string yearbyte = "68CA00CA00684BFFFFFFFF1A106200000100026B6464100068AAAAAAAAAAAA68110434333438B416000000000000000000000000000000009716";
				string bodystatedj = await pluginService.Transform(item.Sn, string.Join("", yearbyte));
				Console.WriteLine("开始抄冻结数据1111111111" + bodystatedj);
				string[] result645dj = ParseDLT645Result(bodystatedj);
				Console.WriteLine("开始抄冻结数据2222222222222" + string.Join("", result645dj));
				string resultdj = ParseDLT645Free(string.Join("", result645dj));
				Console.WriteLine("冻结时间是" + bodystatedj);
				if (!string.IsNullOrEmpty(resultdj) && resultdj != "0000000000")
				{
					uploadMqttInfo.Time = resultdj;
					string[] result645djdata = ParseDLT645Result(await pluginService.Transform(valueCmd: string.Join("", (from u in BaseUtil.GetTransbyte(bytedatatrain, byteinfo, item.Sn)
						select u.ToString("x2")).ToArray()), imei: item.Sn));
					Console.WriteLine("冻结结果是" + result645djdata);
					string resultdjdata = ParseDLT645Free(string.Join("", result645djdata));
					uploadMqttInfo.AllTotalFreeze = resultdjdata;
				}
				dic.Add(item.LowAddr, uploadMqttInfo);
				int newtype = 0;
				LoggerExtension.Info("开始上报数据" + item.Sn + "----" + item.LowAddr + JsonConvert.SerializeObject(dic));
				Console.WriteLine($"测试111111111111111111111{item.Sn}{newtype}{JsonConvert.SerializeObject(dic)}");
				await ePowerService.MeterUpload(item.Sn, newtype, dic);
				continue;
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				LoggerExtension.Error("设备报错啦dingshi定时任务1", ex);
				continue;
			}
		}
	}

	/// <summary>
	/// 冻结特殊处理
	/// </summary>
	/// <param name="body"></param>
	/// <returns></returns>
	private static string ParseDLT645Free(string body)
	{
		if (string.IsNullOrWhiteSpace(body))
		{
			return "";
		}
		List<byte> list = new List<byte>();
		list.Add(254);
		list.Add(254);
		list.Add(254);
		list.Add(254);
		bool sucess = true;
		for (int i = 0; i < body.Length / 2; i++)
		{
			byte byteInfo = (byte)Convert.ToInt32(body.Substring(i * 2, 2), 16);
			if (!(byteInfo == 254 && sucess))
			{
				sucess = false;
				list.Add(byteInfo);
			}
		}
		AgreementAnalysis resultInfo = DL645Agreement.DL645Analysis(list.ToArray());
		if (!resultInfo.Sucess)
		{
			return "";
		}
		if (!string.IsNullOrWhiteSpace(resultInfo.Data))
		{
			if (resultInfo.Data.Length > 8)
			{
				string infoType = resultInfo.Data.Substring(0, 8).ToUpper();
				string infoData = resultInfo.Data.Substring(8);
				return DL645ParameterSet.AnalisReading(infoType, infoData);
			}
			return "";
		}
		return "";
	}

	private string ParseDLT645(string body)
	{
		if (string.IsNullOrWhiteSpace(body))
		{
			return "";
		}
		List<byte> list = new List<byte>();
		list.Add(254);
		list.Add(254);
		list.Add(254);
		list.Add(254);
		bool sucess = true;
		for (int i = 0; i < body.Length / 2; i++)
		{
			byte byteInfo = (byte)Convert.ToInt32(body.Substring(i * 2, 2), 16);
			if (!(byteInfo == 254 && sucess))
			{
				sucess = false;
				list.Add(byteInfo);
			}
		}
		AgreementAnalysis resultInfo = DL645Agreement.DL645Analysis(list.ToArray());
		if (!resultInfo.Sucess)
		{
			throw Oops.Oh(ErrorCodeEnumEx.X1001);
		}
		if (!string.IsNullOrWhiteSpace(resultInfo.Data))
		{
			if (resultInfo.Data.Length > 8)
			{
				string infoType = resultInfo.Data.Substring(0, 8).ToUpper();
				string infoData = resultInfo.Data.Substring(8);
				return DL645ParameterSet.AnalisReading(infoType, infoData);
			}
			return "";
		}
		return "";
	}

	private string[] ParseDLT645Result(string body)
	{
		Console.WriteLine(body + "888888888888888888");
		int index = 28;
		string typeCode = body.Substring(index, 8);
		index += 8;
		if (1 == 0)
		{
		}
		string[] result = typeCode switch
		{
			"01010110" => GetResult129(body, index), 
			"01010103" => GetResult25(body, index), 
			"00000100" => Get645Result(body, index), 
			_ => null, 
		};
		if (1 == 0)
		{
		}
		return result;
	}

	private string[] Get645Result(string body, int index)
	{
		index += 2;
		int length = Convert.ToInt32(body.Substring(index, 2), 16) * 2;
		index += 4;
		string result = body.Substring(index, length);
		string[] info = new string[length / 2];
		for (int i = 0; i < info.Length; i++)
		{
			info[i] = result.Substring(i * 2, 2);
		}
		return info;
	}

	/// <summary>
	/// f.25抄表
	/// </summary>
	/// <param name="body"></param>
	/// <param name="index"></param>
	/// <returns></returns>
	private string[] GetResult25(string body, int index)
	{
		string result = "";
		DateTime time = DateTime.Parse($"20{body.Substring(index + 8, 2)}-{body.Substring(index + 6, 2)}-{body.Substring(index + 4, 2)} {body.Substring(index + 2, 2)}:{body.Substring(index, 2)}");
		index += 10;
		string[] arr = new string[10];
		for (int i = 0; i < 10; i++)
		{
			if (i < 4)
			{
				string binaryValue = Convert.ToString(Convert.ToInt32(body.Substring(index + 4, 2), 16), 2);
				string ten = Convert.ToInt32(binaryValue.PadLeft(8, '0').Substring(1, 3), 2).ToString() ?? "";
				string ge = Convert.ToInt32(binaryValue.PadLeft(8, '0').Substring(4, 4), 2).ToString() ?? "";
				arr[i] = $"{ten}{ge}.{body.Substring(index + 2, 2)}{body.Substring(index, 2)}";
				index += 6;
			}
			else if (i == 4)
			{
				index += 40;
				arr[i] = (body.Substring(index + 2, 2) + body.Substring(index, 2)).Insert(3, ".");
				index += 4;
			}
			else if (i > 4 && i < 7)
			{
				arr[i] = (body.Substring(index + 2, 2) + body.Substring(index, 2)).Insert(3, ".");
				index += 4;
			}
			else
			{
				string binaryValue = Convert.ToString(Convert.ToInt32(body.Substring(index + 4, 2), 16), 2);
				string ten = Convert.ToInt32(binaryValue.PadLeft(8, '0').Substring(1, 3), 2).ToString() ?? "";
				string ge = Convert.ToInt32(binaryValue.PadLeft(8, '0').Substring(4, 4), 2).ToString() ?? "";
				arr[i] = $"{ten}{ge}.{body.Substring(index + 2, 2)}{body.Substring(index, 2)}";
				index += 6;
			}
		}
		return arr.Reverse().ToArray();
	}

	/// <summary>
	/// 129抄表返回
	/// </summary>
	/// <param name="body"></param>
	/// <param name="index"></param>
	/// <returns></returns>
	private string[] GetResult129(string body, int index)
	{
		DateTime time = DateTime.Parse($"20{body.Substring(index + 8, 2)}-{body.Substring(index + 6, 2)}-{body.Substring(index + 4, 2)} {body.Substring(index + 2, 2)}:{body.Substring(index, 2)}");
		index += 10;
		int count = Convert.ToInt32(body.Substring(index, 2));
		index += 2;
		string result = "";
		string[] arr = new string[count + 1];
		for (int i = 0; i < count + 1; i++)
		{
			arr[i] = $"{body.Substring(index + 8, 2)}{body.Substring(index + 6, 2)}{body.Substring(index + 4, 2)}.{body.Substring(index + 2, 2)}{body.Substring(index, 2)}";
			index += 10;
		}
		return arr.Reverse().ToArray();
	}
}
